package ProjectMain;

/* @Author: Ryan Carvalho
 * @Author: Nathan Butler
 * @Author Rhys Higa
* @Version: October 20, 2013
* Generates an ics file from user input to be read into a calendaring system
*/
import java.awt.*;
import java.awt.event.*;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import javax.swing.*;

public class ICalCreator implements ItemListener{
	//A panel that uses CardLayout
	//This will be used to switch between panes in the UI
	JPanel cards; 
	final static String NEWCLASS = "Add New Class";
   final static String NEWEVENT = "Add New Event";
   final static String CREATEDEVENTS = "View Events Created";
   String EVENTTITLE, EVENTLOCATION, EVENTSUMMARY, EVENTRESOURCES = " ";
   ArrayList<Event> ArrayEvents = new ArrayList<Event>();
   String inputFreq = "";
   public void addComponentToPane(Container pane) 
   {
   	//Put the JComboBox in a JPanel to get a nicer look.
       JPanel comboBoxPane = new JPanel(); //use FlowLayout
       String comboBoxItems[] = { NEWEVENT, NEWCLASS, CREATEDEVENTS };
       JComboBox cb = new JComboBox(comboBoxItems);
       cb.setEditable(false);
       cb.addItemListener(this);
       comboBoxPane.add(cb);
       //Create the "cards".
       JPanel events = new JPanel();
       final JTextArea listedEvents = new JTextArea("None", 10, 55);
       listedEvents.setEditable(false);
       listedEvents.setLineWrap(true);
       events.add(listedEvents);
       JButton generate = new JButton("Generate ics file");
       events.add(generate);
       JButton remove = new JButton("Remove events");
       events.add(remove);
       remove.addActionListener(new ActionListener()
       {
       	public void actionPerformed(ActionEvent arg0) 
       	{
       		if(ArrayEvents.size() == 0)
               {
       			JFrame noEvents = new JFrame("No Events!");
                   JOptionPane.showMessageDialog(noEvents, "There are no events!");
               }
               else
               {
               	for(int i = 0; i < ArrayEvents.size(); i++)
                   {
               		ArrayEvents.remove(i);
                   }
                   listedEvents.setText("none");
                   JFrame deleted = new JFrame("Deleted!");
                   JOptionPane.showMessageDialog(deleted, "All events were deleted!");
               }
           }
       });
       generate.addActionListener(new ActionListener()
       {
       	public void actionPerformed(ActionEvent arg0) 
           {
       		String prefix = "BEGIN:VCALENDAR" + "\n" +
                               "VERSION:2.0" + "\n" +
                               "BEGIN:VEVENT" + "\n";
               String suffix = "END:VEVENT" + "\n" +
                               "END:VCALENDAR";
               try 
               {
               	//replace File args to specify directory path
                   File f = new File("/Users/nathanbutler/Desktop/ical.ics");
                   FileWriter fstream = new FileWriter(f);
                   BufferedWriter out = new BufferedWriter(fstream);
                   out.write(prefix);
                   for(int i = 0; i < ArrayEvents.size(); i++)
                   {
                   	out.write(ArrayEvents.get(i).evtIcs());
                   }
                   out.write(suffix);
                   out.close();
               } 
               catch (IOException e) 
               {
               	e.printStackTrace();
               }
               JFrame gen = new JFrame("Generated");
               JOptionPane.showMessageDialog(gen, "ics File was generated!");
           }
       });
       
       //Sections for creating a new calendar event
       final JPanel newEvents = new JPanel();
       final JTextField etitle = new JTextField(20);
       final JTextField elocation = new JTextField(20);
       final JTextField ecomments = new JTextField(20);
       final JTextField eresources = new JTextField(20);
       newEvents.add(new JLabel("Event Title:"));
       newEvents.add(etitle);
       newEvents.add(new JLabel("Event Location:"));
       newEvents.add(elocation);
       newEvents.add(new JLabel("Comments:"));
       newEvents.add(ecomments);
       newEvents.add(new JLabel("Resources: "));
       newEvents.add(eresources);
       newEvents.add(new JLabel("Start Date:"));
       String monthItems[] = {"01", "02", "03", "04", "05", 
                       "06", "07", "08", "09", "10", "11",
                       "12"};
       final JComboBox monthsSTART = new JComboBox(monthItems);
       monthsSTART.setEditable(false);
       newEvents.add(monthsSTART);
       final String DAYS_28[] = {"01", "02", "03", "04", "05", "06", "07", "08", "09", "10",
                       "11", "12", "13", "14", "15", "16", "17", "18", "19", "20",
                       "21", "22", "23", "24", "25", "26", "27", "28"};
       final String DAYS_30[] = {"01", "02", "03", "04", "05", "06", "07", "08", "09", "10",
                       "11", "12", "13", "14", "15", "16", "17", "18", "19", "20",
                       "21", "22", "23", "24", "25", "26", "27", "28", "29", "30"};
       final String DAYS_31[] = {"01", "02", "03", "04", "05", "06", "07", "08", "09", "10",
                       "11", "12", "13", "14", "15", "16", "17", "18", "19", "20",
                       "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31"};
       final JComboBox daysSTART = new JComboBox(DAYS_31);
       daysSTART.setEditable(false);
       newEvents.add(daysSTART);
       monthsSTART.addItemListener(new ItemListener()
       {
       	public void itemStateChanged(ItemEvent evt) 
           {
       		int input = Integer.parseInt((String)evt.getItem());
               if(input == 2)
               {
               	JComboBox days28 = new JComboBox(DAYS_28);
                   daysSTART.setModel(days28.getModel());
               }
               else if(input == 4 || input == 6 || input == 9 || input == 11)
               {
               	JComboBox days30 = new JComboBox(DAYS_30);
                   daysSTART.setModel(days30.getModel());
               }
               else
               {
               	JComboBox days31 = new JComboBox(DAYS_31);
                   daysSTART.setModel(days31.getModel());
               }
           }
       });
       String years[] = {"2013", "2014", "2015", "2016", "2017", "2018"};
       final JComboBox yearSTART = new JComboBox(years);
       yearSTART.setEditable(false);
       newEvents.add(yearSTART);
       newEvents.add(new JLabel("Start Time:"));
       String hours[] = {"01", "02", "03", "04", "05", "06", "07",
                       "08", "09", "10", "11", "12" , "13", "14", "15", "16", "17",
                       "18", "19", "20", "22", "23", "24"};
       String mins[] = {"00", "15", "30", "45"};
       final JComboBox HOURSTART = new JComboBox(hours);
       HOURSTART.setEditable(false);
       final JComboBox MINSTART = new JComboBox(mins);
       MINSTART.setEditable(false);
       newEvents.add(HOURSTART);
       newEvents.add(MINSTART);
       final JLabel endDate = new JLabel("End Date:");
       newEvents.add(endDate);
       final JComboBox monthsEND = new JComboBox(monthItems);
       monthsEND.setEditable(false);
       newEvents.add(monthsEND);
       final JComboBox daysEND = new JComboBox(DAYS_31);
       daysEND.setEditable(false);
       newEvents.add(daysEND);
       monthsEND.addItemListener(new ItemListener()
       {
       	public void itemStateChanged(ItemEvent evt) 
           {
       		int input = Integer.parseInt((String)evt.getItem());
               if(input == 2)
               {
               	JComboBox days28 = new JComboBox(DAYS_28);
                   daysEND.setModel(days28.getModel());
               }
               else if(input == 4 || input == 6 || input == 9 || input == 11)
               {
               	JComboBox days30 = new JComboBox(DAYS_30);
                   daysEND.setModel(days30.getModel());
               }
               else
               {
               	JComboBox days31 = new JComboBox(DAYS_31);
                   daysEND.setModel(days31.getModel());
               }
           }
       });
       final JComboBox yearEND = new JComboBox(years);
       yearEND.setEditable(false);
       newEvents.add(yearEND);
       final JLabel endTime = new JLabel("End Time:");
       newEvents.add(endTime);
       final JComboBox HOUREND = new JComboBox(hours);
       HOUREND.setEditable(false);
       final JComboBox MINEND = new JComboBox(mins);
       MINEND.setEditable(false);
       newEvents.add(HOUREND);
       newEvents.add(MINEND);
       newEvents.add(new JLabel("Recurring Event?"));
       final JCheckBox yesButton;
       yesButton = new JCheckBox("Yes");
       yesButton.setSelected(false);
       newEvents.add(yesButton);
       String rec[] = {"None", "DAILY", "MONTHLY", "YEARLY"};
       final JComboBox frequency = new JComboBox(rec);
       frequency.setEditable(false);
       frequency.setVisible(false);
       newEvents.add(frequency);
       final JLabel until = new JLabel("Until:");
       until.setVisible(false);
       newEvents.add(until);
       final JComboBox monthRec = new JComboBox(monthItems);
       monthRec.setEditable(false);
       monthRec.setVisible(false);
       newEvents.add(monthRec);
       final JComboBox daysRec = new JComboBox(DAYS_31);
       daysRec.setEditable(false);
       daysRec.setVisible(false);
       newEvents.add(daysRec);
       monthRec.addItemListener(new ItemListener()
       {
       	public void itemStateChanged(ItemEvent evt) 
           {
       		int input = Integer.parseInt((String)evt.getItem());
               if(input == 2)
               {
               	JComboBox days28 = new JComboBox(DAYS_28);
                   daysRec.setModel(days28.getModel());
               }
               else if(input == 4 || input == 6 || input == 9 || input == 11)
               {
               	JComboBox days30 = new JComboBox(DAYS_30);
                   daysRec.setModel(days30.getModel());
               }
               else
               {
               	JComboBox days31 = new JComboBox(DAYS_31);
                   daysRec.setModel(days31.getModel());
               }
           }
       });
       final JComboBox yearRec = new JComboBox(years);
       yearRec.setVisible(false);
       yearRec.setEditable(false);
       newEvents.add(yearRec);
       yesButton.addItemListener(new ItemListener()
       {
       	public void itemStateChanged(ItemEvent arg0) 
           {
       		if(yesButton.isSelected())
               {
       			frequency.setVisible(true);
                   until.setVisible(true);
                   monthRec.setVisible(true);
                   daysRec.setVisible(true);
                   yearRec.setVisible(true);
               }
               else if(!yesButton.isSelected())
               {
               	yesButton.setSelected(false);
                   frequency.setVisible(false);
                   until.setVisible(false);
                   monthRec.setVisible(false);
                   daysRec.setVisible(false);
                   yearRec.setVisible(false);
               }
           }               
       });
       JButton subTEXT = new JButton("Create Event");
       newEvents.add(subTEXT);
       
       //Section for creating a new Class event
       final JPanel newClass = new JPanel();
       JLabel crnLabel = new JLabel("CRN Number:");
       final JTextField crn = new JTextField(10);
       JButton add = new JButton("Add");
       newClass.add(crnLabel);
       newClass.add(crn);
       newClass.add(add);
       add.addActionListener(new ActionListener()
       {
			public void actionPerformed(ActionEvent arg0) 
			{
				String result = findCRN(crn.getText());
				Event newClass = classToEvent(result);
				if(newClass.isTBA())
				{
					JFrame tba = new JFrame("Error!");
	                JOptionPane.showMessageDialog(tba, "Class not added. " +
	                		"TBA fields prevented add!");

				}
				else
				{
					JFrame added = new JFrame("Added");
	            	listedEvents.setText(null);
	            	ArrayEvents.add(newClass);
	                for(int i = 0; i < ArrayEvents.size(); i++)
	                {
	                	listedEvents.append("\n" + (i+1 +") ") + ArrayEvents.get(i).toString());
	                }
	                JOptionPane.showMessageDialog(added, "Added Event!");
				}
			}      	
       });
       //Create the panel that contains the "cards".
       cards = new JPanel(new CardLayout());
       cards.add(newEvents, NEWEVENT);
       cards.add(events, CREATEDEVENTS);
       cards.add(newClass, NEWCLASS);
       pane.add(comboBoxPane, BorderLayout.PAGE_START);
       pane.add(cards, BorderLayout.CENTER);
       subTEXT.addActionListener(new ActionListener()
       {
       	public void actionPerformed(ActionEvent action) 
           {
       		String ys = yearSTART.getSelectedItem() + "";
               String ms = monthsSTART.getSelectedItem() +"";
               String ds = daysSTART.getSelectedItem() + "";
               String hs = HOURSTART.getSelectedItem() +"";
               String minS = MINSTART.getSelectedItem() +"";
               final iCalDate startDate = new iCalDate(ys, ms, ds, hs, minS);
               String ye = yearEND.getSelectedItem() + "";
               String me = monthsEND.getSelectedItem() +"";
               String de = daysEND.getSelectedItem() + "";
               String he = HOUREND.getSelectedItem() + "";
               String mine = MINEND.getSelectedItem() + "";
               final iCalDate endDate = new iCalDate(ye, me, de, he, mine);
               if(!yesButton.isSelected())
               {
               	if(startDate.compareTo(endDate) < 0)
                   {
               		JFrame frame = new JFrame("Warning!");
                       JOptionPane.showMessageDialog(frame,
                              "End time was before start time.");
                   }
                   else
                   {
                   	listedEvents.setText(null);
                       EVENTTITLE = etitle.getText();
                       EVENTLOCATION = elocation.getText();
                       EVENTSUMMARY = ecomments.getText();
                       EVENTRESOURCES = eresources.getText();
                       Event e = new Event(EVENTTITLE, EVENTLOCATION, EVENTSUMMARY, 
                            EVENTRESOURCES,startDate, endDate);
                       ArrayEvents.add(e);
                       for(int i = 0; i < ArrayEvents.size(); i++)
                       {
                       	listedEvents.append("\n" + (i+1 +") ") + ArrayEvents.get(i).toString());
                       }
                       etitle.setText(null);
                       elocation.setText(null);
                       ecomments.setText(null);
                       eresources.setText(null);
                       JFrame added = new JFrame("Done!");
                       JOptionPane.showMessageDialog(added, "Added Event!");
                   }
               }
               else
               {
               	String ry = yearRec.getSelectedItem() + "";
                   String rm = monthRec.getSelectedItem() +"";
                   String rd = daysRec.getSelectedItem() + "";
                   inputFreq = frequency.getSelectedItem() + "";
                   final iCalDate recEndDate = new iCalDate(ry,rm,rd,he,mine);
                   listedEvents.setText(null);
                   EVENTTITLE = etitle.getText();
                   EVENTLOCATION = elocation.getText();
                   EVENTSUMMARY = ecomments.getText();
                   EVENTRESOURCES = eresources.getText();
                   Event e = new Event(EVENTTITLE, EVENTLOCATION, EVENTSUMMARY, 
                             EVENTRESOURCES,startDate, endDate, recEndDate, inputFreq);
                   ArrayEvents.add(e);
                   for(int i = 0; i < ArrayEvents.size(); i++)
                   {
                   	listedEvents.append("\n" + (i+1 +") ") + ArrayEvents.get(i).toString());
                   }
                   etitle.setText(null);
                   elocation.setText(null);
                   ecomments.setText(null);
                   eresources.setText(null);
                   JFrame added = new JFrame("Done!");
                   JOptionPane.showMessageDialog(added, "Added Event!");
                }           
           }
       });
   }
   //Method used to switch between cards
   public void itemStateChanged(ItemEvent evt) 
   {
       CardLayout cl = (CardLayout)(cards.getLayout());
       cl.show(cards, (String)evt.getItem());
   }
   /**
    * Create the GUI and show it.  For thread safety,
    * this method should be invoked from the
    * event dispatch thread.
    */
   private static void createAndShowGUI() 
   {
       //Create and set up the window.
       JFrame frame = new JFrame("iCal Creator");
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       //Create and set up the content pane.
       ICalCreator demo = new ICalCreator();
       demo.addComponentToPane(frame.getContentPane());
       //Display the window.
       frame.pack();
       frame.setSize(700, 400);
       frame.setVisible(true);
   }
   public static void main(String[] args) 
   {
       //Schedule a job for the event dispatch thread:
       //creating and showing this application's GUI.
       javax.swing.SwingUtilities.invokeLater(new Runnable() 
       {
           public void run() 
           {
               createAndShowGUI();
           }
       });
   }
   
   public String findCRN(String crn)
   {
   	File f = new File("/Users/nathanbutler/Desktop/ALL.csv");
   	try 
   	{
			BufferedReader br = new BufferedReader(new FileReader(f));
			String line = " ";
			try 
			{
				while((line = br.readLine())!= null)
				{
					String[] tokens = line.split(",");
					if(tokens[0].compareTo(crn) == 0)
					{
						br.close();
						return line;
					}
				}
				br.close();
				return "Class was not found!";
			} catch (IOException e) 
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} 
   	catch (FileNotFoundException e) 
   	{
			return "File was not found!";
		}
   	return "Class was not found!";
   }
   public Event classToEvent(String line)
   {
   	if(line.equalsIgnoreCase("Class was not found!") || 
   			line.equalsIgnoreCase("File was not found!"))
   	{
   		return null;
   	}
   	else
   	{
   		String[] tokens = line.split(",");
   		String summary = tokens[1];
   		String comments = tokens[2];
   		String recur_days[] = dayFormat(tokens[3]);
   		String times[] = convertTime(tokens[4]);
   		String location = tokens[5];
   		String startDate_endDate[] = convertDate(tokens[6]);
   		//Possible bug
   		iCalDate start = new iCalDate("2013",startDate_endDate[0],
   				startDate_endDate[1],times[0]);
   		iCalDate end = new iCalDate("2013", startDate_endDate[0],
   				startDate_endDate[1],times[1]);
   		//Will recur until this date
   		iCalDate rec_end = new iCalDate("2013", startDate_endDate[2],
   				startDate_endDate[3],times[0],times[1]);
   		//The event that holds the class event
   		Event newClass = new Event(summary,location,comments,start
   				,end,rec_end,"WEEKLY",recur_days);
   		return newClass;
   	}
   }
   
   //need to implement TBA days
   public String[] dayFormat(String days)
   {
   	String[] classDays = new String[10];
   	for(int i = 0; i < days.length(); i++)
   	{
   		switch(days.charAt(i))
   		{
   			case 'M':
   			{
   				classDays[i] = "MO";
   				break;
   			}
   			case 'T':
   			{
   				if(days.compareTo("TBA") == 0)
   				{
   					classDays[i] = "TBA";
   					return classDays;
   				}
   				else
   				{
       				classDays[i] = "TU";
       				break;
   				}
   			}
   			case 'W':
   			{
   				classDays[i] = "WE";
   				break;
   			}
   			case 'R':
   			{
   				classDays[i] = "TH";
   				break;
   			}
   			case 'F':
   			{
   				classDays[i] = "FR";
   				break;
   			}
   			case 'S':
   			{
   				classDays[i] = "SA";
   				break;
   			}
   			case 'U':
   			{
   				classDays[i] = "SU";
   				break;
   			}
   			default:
   			{
   				classDays[i] = "TBA";
   				break;
   			}
   		}
   	}
   	return classDays;
   }
   //need to implement TBA timeFrames
   public String[] convertTime(String timeFrame)
   {
		String[] times= new String[2];
   	if(timeFrame.compareTo("TBA") == 0)
   	{
   		times[0] = "TBA";
   		times[1] = "TBA";
   		return times;
   	}
   	else
   	{
   		String tokens[] = timeFrame.split("-");
   		String start = tokens[0];
   		String end = tokens[1];
       	//Time is at night
       	//Convert to 24 time
       	if(timeFrame.charAt(timeFrame.length()-1) == 'p')
       	{
       		int s = Integer.parseInt(start);
       		int e = Integer.parseInt(end.substring(0, end.length()-1));
       		if(s < 1200 || s > 1259)
       		{
       			s += 1200;
       		}
       		if(e < 1200 || e > 1259)
       		{
       			e += 1200;
       		}
       		times[0] = s+"";
       		times[1] = e+"";
       		return times;
       	}
       	//Time is during the morning
       	//Leave as is
       	else
       	{
       		times[0] = tokens[0];
       		times[1] = tokens[1].substring(0, tokens[1].length()-1);
       		return times;
       	}
   	}	
   }
   public String[] convertDate(String date)
   {
   	String start_end[] = new String[4];
		String tokens[] = date.split("-");
		String startTokens[] = tokens[0].split("/");
		String endTokens[] = tokens[1].split("/");
		start_end[0] = startTokens[0];
		start_end[1] = startTokens[1];
		start_end[2] = endTokens[0];
		start_end[3] = endTokens[1];
		return start_end;
	}
}